package cn.edu.njuit.webserver.securityserver.service.impl;

import cn.edu.njuit.webserver.securityserver.entity.Role;
import cn.edu.njuit.webserver.securityserver.entity.UserAccount;
import cn.edu.njuit.webserver.securityserver.entity.UserRole;
import cn.edu.njuit.webserver.securityserver.repository.RoleRepository;
import cn.edu.njuit.webserver.securityserver.repository.UserRepository;
import cn.edu.njuit.webserver.securityserver.repository.UserRoleRepository;
import cn.edu.njuit.webserver.securityserver.service.AccountService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;

@Service
public class AccountServiceImpl implements AccountService {
    private final UserRepository userRepository;
    private final RoleRepository roleRepository;

    private final UserRoleRepository userRoleRepository;

    public AccountServiceImpl(UserRepository userRepository, RoleRepository roleRepository, UserRoleRepository userRoleRepository) {
        this.userRepository = userRepository;
        this.roleRepository = roleRepository;
        this.userRoleRepository = userRoleRepository;
    }

    @Override
    public UserAccount regAccount(String login, String password, String defaultRole) throws Exception {
        //根据登录名查询账户是否存在
        UserAccount account = getAccount(login);
        if(account!=null){
            throw new Exception("登录名已存在，注册失败");
        }
        account = new UserAccount();
        account.setAccountStatus("1");
        account.setLogin(login);
        account.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        account.setRegDate(LocalDateTime.now());
        account=this.userRepository.save(account);
        if(account.getId()>0){
            //查询默认角色id，创建账户对应角色
            Role accountRole = this.roleRepository.findByRoleName(defaultRole);
            if(accountRole==null){
                //默认角色不存在，创建默认角色。
                accountRole=new Role();
                accountRole.setRoleName(defaultRole);
                accountRole=this.roleRepository.save(accountRole);
            }
            if(accountRole.getId()>0){
                UserRole userRole=new UserRole();
                userRole.setUserAccount(account);
                userRole.setRole(accountRole);
                this.userRoleRepository.save(userRole);
            }
            return account;
        }else{
            throw new Exception("账户创建失败");
        }

    }

    @Transactional
    @Override
    public Boolean deleteAccount(String login) throws Exception {
        //根据登录名查询账户是否存在
        UserAccount account = getAccount(login);
        if(account==null){
            throw new Exception("账户不存在");
        }
        try{
            this.userRoleRepository.deleteByUserAccountId(account.getId());
            this.userRepository.deleteById(account.getId());
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public UserAccount getAccount(String login) {
        return this.userRepository.findByLogin(login);
    }

    @Override
    public Page<UserAccount> getAllAccounts(Integer page, Integer size) {

        return this.userRepository.findAll(PageRequest.of(page,size));
    }

    @Override
    public String doLogin(String login, String password) throws Exception {
        UserAccount account = getAccount(login);
        if(account==null){
            throw new Exception("账户不存在");
        }
        String encryptedPassword = account.getPassword();
        if(encryptedPassword.equals(DigestUtils.md5DigestAsHex(password.getBytes()))){
            account.setLastLoginTime(LocalDateTime.now());
            this.userRepository.save(account);
            return "thisisatoken."+account.getLogin()+".tokenend";
        }else{
            throw new Exception("登录密码验证失败");
        }

    }
}
